/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;

import Interaction.ServerConnection;
import java.rmi.RemoteException;

import Flightadministration.*;
import Data.*;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author David Ponce
 * @author Philipp Armbruster
 */
public class AircraftTypeManage extends JPanel {

    final Main td;
    private JPanel jp;
    public DefaultTableModel model;
    public JTable table;
    public Vector<Vector> rowData;
    public Vector<String> columnNames;
    public int currentAircraftTypeId;
    final AircraftTypEdit acte;
    /*Das AdministrationsObjekt, welches über die getConnection methode vom RMI Server geholt wird, dem "admin" objekt zugewiesen.
    *Dadurch ist eine Kommunikation zwischen GUI und Applikationsserver mittels RMI möglich*/
    final Flightadministration admin = ServerConnection.getConnection();


    // Konstruktor
    public AircraftTypeManage(final Main td, final AircraftTypEdit acte) throws RemoteException {

        this.td = td;
        this.acte = acte;
        showAircraftTypeManage();
    }

    
    // Methoden
    public void showAircraftTypeManage() throws RemoteException{

        jp = new JPanel();

        //GridBagLayout
        //**********************************************************************

        GridBagLayout gbl = new GridBagLayout();
        jp.setLayout(gbl);
        jp.setBackground(Color.white);

        GridBagConstraints constraints = new GridBagConstraints();

        constraints.fill = GridBagConstraints.HORIZONTAL;   // wie Komponente Bereich füllen soll
        constraints.weightx = 1;                     // Breite
        constraints.weighty = 1;                    // Höhe
        constraints.insets = new Insets(0,0,1,1);   // Abstände definieren

        //Label
        //**********************************************************************

        JLabel headline = new JLabel("<html><h2 color=blue>Übersicht aller Flugzeugtypen</h2></html>");
        headline.setHorizontalAlignment(JLabel.CENTER);
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.gridwidth = 3;
        jp.add(headline, constraints);

        //JTable
        //**********************************************************************

        // Vector für Spaltenüberschrift mit Werten belegen
        columnNames = new Vector<String>();
        columnNames.add("ID");
        columnNames.add("Typenbezeichnung");
        columnNames.add("Sitzstruktur");

        // Vector mit Daten für JTable belegen
        rowData = admin.getAllTypeOfAircraftsForTable();

        model = new DefaultTableModel( rowData, columnNames );
        model.addTableModelListener(table);
        table = new JTable(model) {
            public boolean isCellEditable(int x, int y) {
                return false;
            }
        };
        table.setModel(model);
        table.setAutoCreateRowSorter(true);
        table.getColumnModel().getColumn(0).setPreferredWidth(60);
        table.getColumnModel().getColumn(1).setPreferredWidth(120);
        table.getColumnModel().getColumn(2).setPreferredWidth(500);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 3;
        table.setPreferredScrollableViewportSize(new Dimension(550,450));
        table.setVisible(true);
        jp.add( new JScrollPane(table), constraints);


        //Buttons
        //**********************************************************************

        JButton button_CreateAircraftType = new JButton("Anlegen");
        constraints.gridwidth = 1;
        constraints.gridx = 0;
        constraints.gridy = 2;
        jp.add(button_CreateAircraftType, constraints);

        JButton button_EditAircraftType = new JButton("Editieren");
        constraints.gridx = 1;
        constraints.gridy = 2;
        jp.add(button_EditAircraftType, constraints);

        JButton button_DeleteAircraftType = new JButton("Löschen");
        constraints.gridx = 2;
        constraints.gridy = 2;
        jp.add(button_DeleteAircraftType, constraints);


        //ActionListener
        //**********************************************************************
        table.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent evt){

                //Nur auf Doppelklick der linken Mousetaste reagieren.
                if(evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() > 1){
                    edit();
                }
            }
        });

        button_CreateAircraftType.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                ((CardLayout) td.rightp.getLayout()).show(td.rightp, "AircraftTypeC");
            }
        });


        button_EditAircraftType.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                } else {
                    edit();
                }
            }
        });


        button_DeleteAircraftType.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                }
                else {

                    int iSelectedRow = table.getSelectedRow();

                    Object[] options = {"Ja", "Nein"};

                    String txt = "<html><p style=\"color:red; text-align: center\">Flugzeugtyp <i><u>"
                                    + table.getModel().getValueAt(iSelectedRow, 1)
                                    + "</i></u> wirklich löschen? <br>"
                                    + "Dabei werden auch alle damit in Verbindung stehenden <br>"
                                    + "Buchungen, Flugdurchführungen und Flugzeuge gelöscht</p></html>";
                    int n = JOptionPane.showOptionDialog(td, txt, "Flugzeugtyp löschen",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    options[1]);

                    if (n == 0) {
                        try {
                            // Id des ausgewählten Flugzeugtyps auslesen
                            Object currentTypeOfAircraftId = table.getModel().getValueAt(iSelectedRow, 0);
                                int currentCraftTypeIdAsInt = Integer.parseInt(currentTypeOfAircraftId.toString());
                            // Name des ausgewählten Flugzeugtyps auslesen
                            Object currentTypeOfAircraftName = table.getModel().getValueAt(iSelectedRow, 1);
                                String currentTypeOfAircraftNameAsString = String.valueOf(currentTypeOfAircraftName);
                            // Id der Sitzstruktur des ausgewählten Flugzeugtyps auslesen
                            Object currentSeatStructure = table.getModel().getValueAt(iSelectedRow, 2);
                                String currentSeatStructureAsString = String.valueOf(currentSeatStructure);
                                    int index2 = currentSeatStructureAsString.indexOf("(") - 1;
                                        int currentSeatIdAsInt = Integer.parseInt(currentSeatStructureAsString.substring(13, index2));

                            // Flugzeugtypobjekt aus der Datenbank löschen
                            admin.deleteTypeOfAircraft(currentCraftTypeIdAsInt, currentTypeOfAircraftNameAsString, currentSeatIdAsInt);
                                // JTables aktualisieren
                                td.updateAircraftType();

                            JOptionPane.showMessageDialog(null, "Flugzeugtyp gelöscht");

                        } catch (RemoteException ex) {
                            Logger.getLogger(AirportManage.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        });
    }

    
    public void edit() {
        
        int iSelectedRow = table.getSelectedRow();
        Object currentACTasObject = table.getModel().getValueAt(iSelectedRow, 0);
           String currentACTasString = String.valueOf(currentACTasObject);
                currentAircraftTypeId = Integer.parseInt(currentACTasString);

                    try {
                        TypeOfAircraft a = admin.getTypeOfAircraftById(currentAircraftTypeId);

                        String id = String.valueOf(a.getCraftTypeId());

                        acte.textfield1.setText(a.getCraftTypeName());

                        acte.label2.setText(id);

                        // Sitzstruktur auslesen und übergeben
                        acte.label5.setText(String.valueOf(table.getModel().getValueAt(iSelectedRow, 2)));

                        ((CardLayout) td.rightp.getLayout()).show(td.rightp, "AircraftTypeE");
                    } catch (RemoteException ex) {
                        Logger.getLogger(PassengerManage.class.getName()).log(Level.SEVERE, null, ex);
                    }
    }

    public void updateTableData() throws RemoteException {

        // Vector mit Daten für JTable belegen
        rowData = admin.getAllTypeOfAircraftsForTable();

        // Tabelleninhalt wird aktualisiert
        model.setDataVector(rowData, columnNames);

    }

    public JPanel getJp() {
        return jp;
    }
}